import json

from django.db.models import Q, F
from django.http import HttpResponse
from django.shortcuts import render

from apps.fun import seng_sys_msg
from h5.models import ChatUser, UserRelation, UserGroup, ChatMsg, Groups, OnlineUser


def ajax_ok(data):
    data = json.dumps(data)
    return HttpResponse(data)

def login(request):
    """"""
    username = request.GET.get('username','')
    if username:
        user,_ = ChatUser.objects.get_or_create(username=username,defaults=dict(
            username=username,logins=1
        ))

        return ajax_ok(dict(uid=user.id,username=user.username))
    return render(request,'login/login.html')


def sy(request):
    """"""
    uid = request.GET.get('uid','0')
    user = ChatUser.objects.filter(id=uid).last()
    data = dict(uid=uid,username=user.username)
    # 我的好友
    user_relation = UserRelation.objects.filter(uid=uid,status=1).values('obj_uid','last_msg_info')
    # 我的群
    user_group_id = list(UserGroup.objects.filter(uid=uid).values_list('gid',flat=True))
    user_group = Groups.objects.filter(id__in=user_group_id).values('id','name','last_msg_info')

    user_id_names = dict(
        ChatUser.objects.values_list('id', 'username'))
    # 消息列表
    obj_list = []
    for i in user_relation:
        row = {}
        row['type'] = 1
        row['obj_id'] = i.get('obj_uid')
        last_msg_info = i.get('last_msg_info',{})
        row['obj_name'] = user_id_names.get(i.get('obj_uid'))
        row['last_msg_time'] = last_msg_info.get('time', '')
        row['last_msg_txt'] = last_msg_info.get('last_msg_txt','')
        row['send'] = '我' if last_msg_info.get('is_self',1) == 1 else row['obj_name']
        obj_list.append(row)
    for i in user_group:
        row = {}
        row['type'] = 2
        row['obj_id'] = i.get('id')
        row['obj_name'] = i.get('name')
        last_msg_info = i.get('last_msg_info', {})
        row['last_msg_time'] = last_msg_info.get('time', '')
        row['last_msg_txt'] = last_msg_info.get('last_msg_txt', '')
        row['send'] = '我' if last_msg_info.get('is_self', 1) == 1 else row['obj_name']
        obj_list.append(row)
    obj_list.sort(key=lambda x:x.get('last_msg_time'),reverse=True)
    data['obj_list'] = obj_list
    data['all_user'] = [dict(id=k,name=v) for k,v in user_id_names.items()]
    data['all_qun'] = list(Groups.objects.values_list('name',flat=True))
    return render(request,'sy.html',data)


def get_msg(request):
    uid = int(request.GET.get('uid'))
    obj_id = int(request.GET.get('obj_id'))
    type = int(request.GET.get('type',1))   # 1 好友 2 群
    if type == 1:
        obj = ChatMsg.objects.filter(type=1,msg_from__in=[uid,obj_id],msg_to__in=[uid,obj_id]).values('text','add_time','msg_from','msg_to')
        uids = [uid,obj_id]
    else:
        obj = ChatMsg.objects.filter(type=2,msg_to=obj_id).values('text','add_time','msg_from','msg_to')
        uids = [i.get('msg_from') for i in obj]
    user_names = dict(ChatUser.objects.filter(id__in=uids).values_list('id','username'))
    obj_list = []
    for i in obj:
        obj_list.append(dict(
            msg_from = user_names.get(i.get('msg_from')),
            msg_to = user_names.get(i.get('msg_to')) if type == 1 else '',
            is_self = 1 if i.get('msg_from') == uid else 0,
            text = i.get('text'),
            t = str(i.get('add_time').strftime('%Y-%m-%d %H:%M:%S'))
        ))

    return ajax_ok(obj_list)

def add_obj(request):
    uid = int(request.GET.get('uid'))
    obj = request.GET.get('obj')
    type = int(request.GET.get('type', 1))  # 1 好友 2 群
    if type == 1:
        if uid == int(obj):
            return ajax_ok(dict(status=0,error='你不能加你自己'))
        if UserRelation.objects.filter(uid=uid,obj_uid=obj).exists():
            return ajax_ok(dict(status=0,error='你已经添加过该用户'))
        if not ChatUser.objects.filter(id=obj).exists():
            return ajax_ok(dict(status=0, error='没有该用户'))
        UserRelation.objects.create(uid=uid,obj_uid=obj,status=1,last_msg_info={})
        UserRelation.objects.create(uid=obj, obj_uid=uid, status=1, last_msg_info={})
        obj_user = OnlineUser.objects.filter(uid=obj).last() # 好友在线，发送消息
        if obj_user:
            user_names = dict(ChatUser.objects.filter(id__in=[uid,obj]).values_list('id','username'))
            seng_sys_msg(dict(id=obj,_from=user_names[int(uid)],_to=user_names[int(obj)],channel_name=obj_user.channel_name))
    else:
        group,_ = Groups.objects.get_or_create(name=obj,defaults=dict(name=obj,last_msg_info={}))

        if UserGroup.objects.filter(gid=group.id,uid=uid).exists():
            return ajax_ok(dict(status=0,error='你已经添加过该群'))
        UserGroup.objects.create(gid=group.id,uid=uid)

    return ajax_ok(dict(status=1))
